import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeVue from '@/views/HomeVue'
import FindVue from '@/views/FindVue'
import InfoVue from '@/views/InfoVue'
import MyVue from '@/views/MyVue'
import LayOut from '@/views/LayOut'
import LoginVue from '@/views/LoginVue'
import RegisterVue from '@/views/RegisterVue'
import { getToken } from '@/utils/storage'
//
import NavBar from '@/components/NavBar'
import MyCollection from '@/components/MyCollection'
import MyRent from '@/components/MyRent'
//
import RentByMap from '@/views/RentByMap'
import AddRentHouses from '@/views/AddRentHouses'
import DetailVue from '@/views/DetailVue'
import CityList from '@/views/CityList'
import Search from '@/views/SearchVue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: LoginVue,
      children: [{ path: '/navbar', component: NavBar }]
    },
    {
      path: '/register',
      component: RegisterVue
    },
    {
      path: '/',
      component: LayOut,
      redirect: '/my',
      children: [
        { path: '/home', component: HomeVue },
        { path: '/find', component: FindVue },
        { path: '/info', component: InfoVue },
        { path: '/my', component: MyVue }
      ]
    },
    { path: '/map', component: RentByMap },
    { path: '/collection', component: MyCollection },
    { path: '/rent', component: MyRent },
    { path: '/add', component: AddRentHouses },
    { path: '/detail/:id', component: DetailVue },
    { path: '/city', component: CityList },
    { path: '/search', component: Search }
  ]
})

// 白名单
const whiteList = ['/login', '/find', '/home', '/register', '/my', '/info', '/map']
// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
